
package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Role;//huibati
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati


/**
 * #{description}
 *
 * @author Administrator
 * @version 1.00
 */
@Service
@Scope("prototype")
public class AdminUserService<T>{
    private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;

    @Autowired
    protected GenericService dslJpaService;

    /**
     * 获取后台管理员用户列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getAdminUserList(Map<String ,Object> values){
    	
		logger.debug("获取后台管理员用户列表");
		
		List<Map<String ,Object>> userList = new ArrayList<Map<String ,Object>>();
		
		String query = "select u from User u , Role r where u.role.id = r.id and u.delStatus != 1";
		
		String roleCode = (String)values.get("roleCode");
		if(roleCode != null && !roleCode.isEmpty()){
			query = query + " and r.code = '"+roleCode+"'";
		}else{
			query = query + " and r.code not in ('reg-enterprises','reg-customer_service')";
		}
		
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and u.loginName like '%"+loginName+"%'";
		}
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and u.name like '%"+name+"%'";
		}
		String phone = (String)values.get("phone");
		if(phone != null && !phone.isEmpty()){
			query = query + " and u.phone like '%"+phone+"%'";
		}
		String status = (String)values.get("status");
		if(status != null && !status.isEmpty()){
			query = query + " and u.status = "+status;
		}
		query = query +" order by u.createTime desc";
		//获取用户列表
		Query qu = (Query) this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
		
		for(int i = 0 ; i < resultList.size() ; i ++){
			User user = (User) resultList.get(i);
			Map<String ,Object> userMap = new HashMap<String, Object>();
			String userID= user.getId().toString();
			userMap.put("userID", userID);//用户id
			String loginNameStr = user.getLoginName();
			userMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			String nameStr = user.getName();
			userMap.put("name", nameStr==null?nameStr="":nameStr);//真是姓名
			Role role = user.getRole();
			if(role != null){
				String roleName = role.getName();
				userMap.put("roleName", roleName==null?roleName="":roleName);//角色名称
			}
			String phoneStr = user.getStaffTel();
			userMap.put("phone", phoneStr==null?phoneStr="":phoneStr);//手机号码
			String email = user.getStaffMail();
			userMap.put("email", email==null?email="":email);//电子邮箱
			Short statusSh = user.getStatus();
			userMap.put("status", statusSh==null?statusSh=5:statusSh);//用户状态 5 null
//			Short sexNum = user.getSex();
//			String sex = "";
//			if(sexNum != null){
//				sex = ICommonConstants.GENDER.values()[sexNum].label();
//			}
//			userMap.put("sex", sex);//性别
			String createTime = "";
			Integer createTimeInt =  user.getCreateDateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			userMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  user.getLastUpdateDateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			userMap.put("updateTime",updateTime);//修改时间
			String remark = user.getRemark(); 
			userMap.put("remark", remark==null?remark="":remark);//备注
			
			userList.add(userMap);
		}
		
        return userList;
    }
    
    /**
     * 获取后台管理用户列表总条数
     * @param values
     * @return
     */
    public int getAdminUserListCount(Map<String ,Object> values){
    	
		logger.debug("获取后台管理用户列表总条数");
		
		String query = "select count(u.id) from User u , Role r where u.role.id = r.id and u.delStatus != 1";
		
		String roleCode = (String)values.get("roleCode");
		if(roleCode != null && !roleCode.isEmpty()){
			query = query + " and r.code = '"+roleCode+"'";
		}else{
			query = query + " and r.code not in ('reg-enterprises','reg-customer_service')";
		}
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and u.loginName like '%"+loginName+"%'";
		}
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and u.name like '%"+name+"%'";
		}
		String phone = (String)values.get("phone");
		if(phone != null && !phone.isEmpty()){
			query = query + " and u.phone like '%"+phone+"%'";
		}
		String status = (String)values.get("status");
		if(status != null && !status.isEmpty()){
			query = query + " and u.status = "+status;
		}
		
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 增加后台管理用户
     * @return
     */
    @Transactional
    public void addAdminUser(User user){
    	
		logger.debug("增加后台管理用户");
		
		String roleCode = user.getRole().getCode();
		Role role = (Role) this.em.createQuery("select r from Role r where r.code = ?1")
				.setParameter(1, roleCode)
				.getSingleResult();
		user.setRole(role);
		user.setStatus((short) 3);
		user.setCreateDateTime(CommonUtil.getCurrTimes());
		user.setLastUpdateDateTime(CommonUtil.getCurrTimes());
		user.setDelStatus((short) 0);
		
		dslJpaService.setEntityClass(User.class);
		dslJpaService.create(user);
		
    }
    
    /**
     * 删除后台管理用户
     * @return
     */
    @Transactional
    public void deleteAdminUser(long userID){
    	
		logger.debug("删除后台管理用户");
		String query = "update User u set u.delStatus = ?1 , u.updateTime = ?2 where u.id = ?3";
		
		//修改用户信息
        this.em.createQuery(query)
                .setParameter(1, (short)1)//已删除
                .setParameter(2, CommonUtil.getCurrTimes())
                .setParameter(3, userID)
                .executeUpdate();
		
    }
    
    /**
     * 修改后台管理用户
     * @return
     */
    @Transactional
    public void updateAdminUser(User user){
    	
		logger.debug("修改后台管理用户");
		String query = "update User u set u.name = ?1 , u.phone = ?2 , u.email = ?3 ,u.sex = ?4 ,u.remark = ?5 , u.updateTime = ?6 ,u.role.id = ?8";
		String password = user.getPassword();
		if(password != null && !password.isEmpty()){
			query = query + ", u.password = '"+password+"'";
		}
		query = query + " where u.id = ?7";
		
		String roleCode = user.getRole().getCode();
		Role role = (Role) this.em.createQuery("select r from Role r where r.delStatus != 1 and r.code = ?1")
				.setParameter(1, roleCode)
				.getSingleResult();
		
		//修改用户信息
        this.em.createQuery(query)
                .setParameter(1, user.getName())
//                .setParameter(2, user.getPhone())
//                .setParameter(3, user.getEmail())
//                .setParameter(4, user.getSex())    //huibati
                .setParameter(5, user.getRemark())
                .setParameter(6, CommonUtil.getCurrTimes())
                .setParameter(7, user.getId())
                .setParameter(8, role.getId())
                .executeUpdate();
    }
    
    /**
     * 查看后台管理用户详情
     * @return
     */
    public Map<String ,Object> getAdminUser(User u){
    	
		logger.debug("查看后台管理用户详情");
		
		Map<String ,Object> userMap = new HashMap<String, Object>();
		
		Long userId = u.getId();
		if(userId != null){
			User user = this.em.find(User.class, userId);
			String userID= user.getId().toString();
			userMap.put("userID", userID);//用户id
			String loginNameStr = user.getLoginName();
			userMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			String nameStr = user.getName();
			userMap.put("name", nameStr==null?nameStr="":nameStr);//真是姓名
			Role role = user.getRole();
			if(role != null){
				String roleCode = role.getCode();
				userMap.put("roleCode", roleCode==null?roleCode="":roleCode);//角色名称
			}
			String phoneStr = user.getStaffTel();
			userMap.put("phone", phoneStr==null?phoneStr="":phoneStr);//手机号码
			String email = user.getStaffMail();
			userMap.put("email", email==null?email="":email);//电子邮箱
			Short statusSh = user.getStatus();
			userMap.put("status", statusSh==null?statusSh=5:statusSh);//用户状态 5 null
//			Short sexNum = user.getSex();
//			userMap.put("sex", sexNum);//性别
			
			String remark = user.getRemark(); 
			userMap.put("remark", remark==null?remark="":remark);//备注
		}
		return userMap;
    }
}
